import { defineStore } from "pinia";
import { ref } from "vue";
import { LoginApi } from "@/apis/useLogin";
import { ShopCartStore } from "./shopCart";
import { margeCarAPI , shopNewCartAPI} from '@/apis/shopCart'
export const useStateStore = defineStore('useState', () => {
  const shopCart = ShopCartStore()
  // 1. 定义管理用户数据的state
  const userInfo = ref({})
  // 2. 定义获取接口数据的action函数
  const getUserInfo = async ({ account, password }) => {
    const { data: res } = await LoginApi({ account, password })
    userInfo.value = res.result
    /* 合并购物车 */
    margeCarAPI(shopCart.cartList.map(item => {
      return {
        skuId: item.skuID,
        count: item.count,
        selected: item.selected
      }
    }))
    shopNewCartAPI()
  }

  /* 退出时清除用户数据 */
  const clearUserInfo = () => {
    userInfo.value = {}
    shopCart.emptyCart()
  }
  // 3. 以对象的格式把state和action return
  return {
    getUserInfo,
    userInfo,
    clearUserInfo
  }
}, { persist: true })